package com.gitee.jjnnzb.designpatterninspring.business.login.handler.impl;

import com.gitee.jjnnzb.designpatterninspring.business.login.entity.bo.ThirdPartyLoginParam;
import com.gitee.jjnnzb.designpatterninspring.business.login.handler.LoginTemplate;
import com.gitee.jjnnzb.designpatterninspring.business.login.manager.LoginCheckManager;
import com.gitee.jjnnzb.designpatterninspring.business.login.manager.LoginRecordManager;
import com.gitee.jjnnzb.designpatterninspring.business.login.manager.TokenGenerateManager;
import com.gitee.jjnnzb.designpatterninspring.common.enums.LoginVersionEnum;
import com.gitee.jjnnzb.designpatterninspring.common.util.JwtTokenUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author Jjn
 * @since 2023/8/8 13:42
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class ThirdPartyLoginTemplateImpl extends LoginTemplate {
    
    // 导入所需要的数据库层及manager层资源
    private final LoginCheckManager loginCheckManager;
    
    private final TokenGenerateManager tokenGenerateManager;
    private final LoginRecordManager loginRecordManager;
    
    @Override
    protected void checkCaptcha(Map<String, Object> map) {
        // 不做校验
    }
    
    @Override
    protected void checkSystemPrivilege(Map<String, Object> map) {
        // check user related system privileges...
        loginCheckManager.checkSystemPermission(map);
    }
    
    @Override
    protected void checkLoginIp(Map<String, Object> map) {
        // do not check...
    }
    
    @Override
    protected void checkUser(Map<String, Object> map) {
        // check userName only...
        loginCheckManager.checkUserAndPassword(map);
    }
    
    @Override
    protected void generateToken(Map<String, Object> map) {
        // generate token...
        tokenGenerateManager.generateToken(map);
    }
    
    @Override
    protected void saveLoginRecord(Map<String, Object> map) {
        // save login record...
        loginRecordManager.saveLoginRecords(map);
    }
    
    @Override
    protected void analyseRequestInfo(Map<String, Object> map) {
        String token = (String) map.get("token");
        String clientId = JwtTokenUtil.getClientId(token);
        // 查询配置表,非可信的clientId不允许生成Token
        if (log.isInfoEnabled()) {
            log.info("查询配置表，校验ClientId:{}是否在配置范围内", clientId);
        }
        ThirdPartyLoginParam params = (ThirdPartyLoginParam) map.get("params");
        map.put("userName", params.getUserName());
        map.put("systemCode", params.getSystemCode());
    }
    
    @Override
    protected String getVersion() {
        return LoginVersionEnum.THIRD_PARTY_V1.getVersion();
    }
}
